<?php
/**
 *  Created by liecol on 2015/4/28.
 */
class MiContentAction extends Action {
	/**
	 * [getList 获取素材列表]
	 * @param  [type]  $title [标题]
	 * @param  integer $start [偏移量]
	 * @param  integer $limit [获取数]
	 * @return [type]         [objArray]
	 */
	public function getList($title=NUll,$start=0,$limit=10,$isExport=0){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		Session::switchCustomer($cid);
		$where['mcont.deleted'] = 0;
		$where["mcont.type"]=array("EXP","=0 or mcont.type is null");
		if (!empty($title)) {
			$where['mcont.title'] = array('like', "%$title%");
		}

		$where['mcont.fromCustomerId'] = array('eq', $cid);
		if(!$isExport){
			$arr = $MicontentModel->alias('mcont')
				->join("LEFT JOIN  wx_micontent_tag_list as tagl ON tagl.webPageId = mcont.id")
				->join("LEFT JOIN  wx_micontent_tag as tag ON tagl.tagId = tag.id")
				->join("wx_mishare sta on mcont.id=sta.moduleId and sta.module='micontent'")
				->where($where)
				->limit($start,$limit)
				->field("mcont.*,GROUP_CONCAT(tag.tagName) as tagNames,sta.viewUv as uv")
				->order('mcont.createTime desc')
				->group("mcont.id")
				->select();

			if ($arr) {
				$count = $MicontentModel->alias('mcont')
					->join("wx_mishare sta on mcont.id=sta.moduleId and sta.module='micontent'")
					->where($where)
					->field("mcont.*")
					->order('mcont.createTime desc')
					->count();
				Output::instance()->objArray($arr,$count);
			}else{
				Output::instance()->resultCode(code_success);
			}
		}else{
			//导出Excel
			$arr = $MicontentModel->alias('mcont')
				->join("LEFT JOIN  wx_micontent_tag_list as tagl ON tagl.webPageId = mcont.id")
				->join("LEFT JOIN  wx_micontent_tag as tag ON tagl.tagId = tag.id")
				->join("wx_mishare sta on mcont.id=sta.moduleId and sta.module='micontent'")
				->where($where)
				->field("mcont.title,GROUP_CONCAT(tag.tagName) as tagNames,sta.viewUv as uv,mcont.updateTime")
				->order('mcont.createTime desc')
				->group("mcont.id")
				->select();
			$expCellName  = array(
				array('title','标题'),
				array('tagNames','标签'),
				array('uv','阅读人数'),
				array('updateTime','时间')
			);
			Output::instance()->objArrayExcel('内容管理', $expCellName, $arr);
		}

	}
	public function getAllContentList($title=null,$cid=null,$start=0,$limit=10){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		Session::switchCustomer($customerId);
		$where['mcont.deleted'] = 0;
		$where["mcont.type"]=array("EXP","=0 or mcont.type is null");
		$cid?$where['mcont.fromCustomerId']=array("eq",$cid):"";
		$title?$where['mcont.title']=array("like","%$title%"):"";
		$arr = $MicontentModel->alias('mcont')
			->join("LEFT JOIN  wx_micontent_tag_list as tagl ON tagl.webPageId = mcont.id")
			->join("LEFT JOIN  wx_micontent_tag as tag ON tagl.tagId = tag.id")
			->join("wx_customer_user cuser on mcont.fromCustomerId = cuser.customerId and cuser.agent='business'")
			->where($where)
			->limit($start,$limit)
			->field("mcont.*,GROUP_CONCAT(tag.tagName) as tagNames,cuser.fullName")
			->order('mcont.createTime desc')
			->group("mcont.id")
			->select();
		if ($arr) {
			$count = $MicontentModel->alias('mcont')
				->join("wx_customer_user cuser on mcont.fromCustomerId = cuser.customerId and cuser.agent='business'")
				->where($where)
				->order('mcont.createTime desc')
				->count();
			Output::instance()->objArray($arr,$count);
		}else{
			Output::instance()->resultCode(code_success);
		}
	}

	//分享详情
	public function shareInfo($module,$moduleId,$name='',$fullName='',$phone='',$start=0,$limit=10,$isExport=0){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer($cid);
		$shareLog = M("share_log");
		$where['a.module']=array("eq",$module);
		$where['a.moduleId']=array("eq",$moduleId);
		$name?$where['b.nickname']=array("like","%$name%"):"";
		$fullName?$where['b.fullName']=array("like","%$fullName%"):"";
		$phone?$where['b.phone']=array("like","%$phone%"):"";
		if(!$isExport){
			$arr = $shareLog->alias("a")
				->join("left join wx_".$cid."_user_weixin_info b on a.fromUserName=b.openid")
				->field("a.uv,a.createTime,b.nickname,b.headimgurl,b.fullName,b.phone")
				->where($where)
				->limit($start,$limit)
				->order("a.uv desc")
				->select();
			if($arr){
				$count = $shareLog->alias("a")
					->join("inner join wx_".$cid."_user_weixin_info b on a.fromUserName=b.openid")
					->where($where)
					->count();
				Output::instance()->objArray($arr,$count);
			}else{
				Output::instance()->object([
					'code'=>-1,
					'total'=>0,
					'results'=>[]
				]);
			}
		}else{
			$arr = $shareLog->alias("a")
				->join("left join wx_".$cid."_user_weixin_info b on a.fromUserName=b.openid")
				->join("left join wx_".$cid."_user c on a.fromUserName=c.userName")
				->field("c.fullName,c.phone,b.nickname,a.uv,a.createTime")
				->where($where)
				->order("a.uv desc")
				->select();
			foreach($arr as $key=>$value){
                $nickname = json_encode($value['nickname']);
                $nickname = preg_replace("/\\\u[ed][0-9a-f]{3}\\\u[ed][0-9a-f]{3}/","*",$nickname);//替换成*
                $arr[$key]['nickname'] = json_decode($nickname);
            }
			$expCellName  = array(
				array('fullName','姓名'),
				array('phone','电话'),
				array('nickname','分享人'),
				array('uv','阅读人数'),
				array('createTime','首次访问时间')
			);
			Output::instance()->objArrayExcel('分享详情', $expCellName, $arr);
		}

	}
	/**
	 * [getContentById 根据id拿取素材数据]
	 * @param  [type] $id [id]
	 * @param  int $platType  /区分老平台还是新平台, 老平台0(默认), 新平台1
	 * @return [type]     [object]
	 */
	public function getContentById($id, $platType=0,$retype=1){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = session('customerId');
        $AccessTagmodel = D('access_tag');
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		/*$shareTopModel = M("mishare_top");
		$shareModel = M("mishare");*/
		$customerUser = M("customer_user");
		$VendorModel = M("mivendor");
		$pbTemplateModel = M("pb_template");
		$ContentTagListModel = M("micontent_tag_list");
		$supplyContent = M("module_supply_chain_content");
		$userId = session("id");
		$customerUserInfo = $customerUser->where("id=$userId")->field("supplyRelation,supplyChainId")->find();
		$where['mcont.id'] = $id;
		if($platType){
			$where['mcont.fromCustomerId'] = $cid;
		}
		if($retype==2) {
			$gg_where['id'] = $id;
			$arr=$MicontentModel
				->where($gg_where)
				->find();
		}else{
			$where['s.module']='micontent';
			$arr = $MicontentModel->alias('mcont')
				->join('inner join wx_mishare s ON s.moduleId=mcont.id')
				->join('inner join wx_mishare_material mm ON s.id=mm.sId')
				->join('wx_mivendor v ON v.id=mcont.vId')
				->join('wx_miyouquan quan ON mcont.qid=quan.id')
				->where($where)
				->field("mcont.*,mm.shareImg,mm.title as shareTitle,mm.shareImg1,v.name as vendorName,s.id as sid,quan.name as quanName")
				->find();
			//var_dump($MicontentModel->getLastSql());exit;
			if($customerUserInfo['supplyRelation']==1){
				$supplyContentInfo = $supplyContent->where("contentId=$id")
					->field("group_concat(cId) as channels,group_concat(isAllChannel) as isAllChannel")
					->find();
				$arr = array_merge($arr,$customerUserInfo,$supplyContentInfo);
			}
		}



		/*由于后续正文内容上传到OSS,为了兼容老平台,新增部分改动,2017-7-6*/
		//判断是否存在OSS链接,存在证明新平台上传的,那么从OSS链接获取正文内容,否则返回content中内容
		if($platType){
			//默认返回content中内容
			if($arr['ossLink']){
				$ossContent = file_get_contents($arr['ossLink']);
				$arr['content'] = $ossContent;
			}
			//获取供应商名称和模版名称
			if($arr['vId']){
				$arr['vname'] = $VendorModel->where(['id' => $arr['vId']])->getField('name');
			}
			if($arr['tplid']){
				$arr['tplname'] = $pbTemplateModel->where(['id' => $arr['tplid']])->getField('tplname');
			}
		}

		if ($arr) {
			$webPageId = $arr["id"];
			$arrTag = $ContentTagListModel->alias("taglist")->where("webPageId=$webPageId")
				->join('wx_micontent_tag tag ON taglist.tagId=tag.id')
				->field("GROUP_CONCAT(tag.id) as tagsId,GROUP_CONCAT(tag.tagName) as tagsName")->find();
			$arr["tags"] = $arrTag["tagsId"];
			$arr["tagsName"] = $arrTag["tagsName"];
			$TagWhere['id'] = array('in', $arr['accessTag']);
            $arr["accessTagsName"] = $AccessTagmodel->where($TagWhere)->getField('GROUP_CONCAT(tagName) as AccessTagsName');
			if($retype==2){
				$gg_status['articleId']=array('eq',$id);
				$gg_status['status']=array('eq','draft');
				$gg = M('gg_article_status')->where($gg_status)->find();
				$arr['refuseTime'] = $gg['refuseTime'];
				$arr['reason']     = $gg['reason'];
				$arr['status']     = $gg['status'];
			}
			Output::instance()->object($arr);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * [saveContent 保存素材数据]
	 * @param  [type]   []
	 * @return [type]  [resultCode]
	 */
	public function saveContent($id=NULL,$vId=NULL, $title=NULL,$tplId=NULL, $picUrl=NULL,$picUrl1="",$recomment=NULL,
								$content=NULL,$tags=NULL, $tplId=NULL,$focusLink=NULL,$isRecommend=Null,$accessTag=NULL,
								$shareImgs=NULL,$shareImgs1=NULL,$description=NUll,$publishTime=null,$associatedShop=null,
								$type=0,$channels=null,$isAllChannel=0){

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		if(!empty($accessTag)){
			addAccessTags($accessTag);
		}
		$cid = Session::$user["customerId"];
		$pid=$id;
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		$ContentTagListModel = M("micontent_tag_list");
		$shareBaseModel=M("mishare");
		$shareMaterModel=M("mishare_material");
		$supplyMicontent = M("module_supply_chain_content");
		$time = date("Y-m-d H:i:s");
		$data["fromCustomerId"] = $cid;
		$data["vId"] = $vId;
		$data["title"] = $title;
		$data["picUrl"] = $picUrl;
		$data["picUrl1"]=$picUrl1;
		$data["recomment"]=$recomment;
		$data["isRecommend"]=$isRecommend;
		$data["content"]=$content;
		$data["accessTag"] = $accessTag;
		$data["tags"] = $tags;
		$data["tplid"] = $tplId;
		$data["focusLink"] = $focusLink;
		$data["description"] = $description;
		$data["createTime"] = $time;
		$data["updateTime"] = $time;
		$data["associatedShop"]=$associatedShop;
		$data["publishTime"] = $publishTime;
		$data["type"] = $type;
		if($publishTime==null){
			$data["publishTime"] = $time;
		}
		$MicontentModel->startTrans();
		if($id) {
			$resultPro = $MicontentModel->where("id=$id")->save($data);
		} else{
			$resultPro = $MicontentModel->add($data);
			$id=$resultPro;
		}
		//分享基础表
		$shareBaseData=array(
			"module" => "micontent" ,
			"moduleId" => $id ,
			"shareCount" => 0 ,
			"viewCount" => 0 ,
			"praiseCount" => 0 ,
			"commentCount" => 0 ,
			"createTime"=> $time,
			"deleted" => 0
		);
		//分享素材表
		$shareMaterData=array(
			"title" => $title,
			"shareImg" => $shareImgs,
			"shareImg1" => $shareImgs1,
			"description" => $description,
			"deleted"=>0
		);
		$shareBaseWhere["module"]="micontent";
		$shareBaseWhere["moduleId"]=$id;
		if($pid) {
			$resultBase=$shareBaseModel->where($shareBaseWhere)->save($shareBaseData);
			//修改分享素材表
			$resultBaseList=$shareBaseModel->where($shareBaseWhere)->find();
			if($resultBaseList) {
				$baseId=$resultBaseList["id"];
				$resultMeter=$shareMaterModel->where('sId=' . $baseId)->save($shareMaterData);
			}
		} else {
			$resultBase=$shareBaseModel->add($shareBaseData);
			//添加素材表
			if($resultBase ) {
				$shareMaterData["sId"]=$resultBase;
				$resultMeter=$shareMaterModel->add($shareMaterData);
			}
		}
		Session::switchCustomer($cid);
		if ($resultPro) {
			$arrTag = explode(",", $tags);
			$ContentTagListModel->where("webPageId=$id")->delete();
			if($tags != ''){
				foreach ($arrTag as $tagId) {
					$dataTagList["tagId"] = $tagId;
					$dataTagList["webPageId"] = $id;
					$dataTagList["fromCustomerId"] = $cid;
					$ContentTagListModel->add($dataTagList);
				}
			}
		}
		if($channels){
			$channels=explode(",",$channels);
			$supplyMicontent->where("contentId=$id")->delete();
			foreach($channels as $key=>$value){
				$supplyData['contentId']=$id;
				$supplyData['cId']=$value;
				$supplyData['isAllChannel']=0;
				$supplyMicontent->add($supplyData);
			}
		}
		if($isAllChannel){
			$supplyMicontent->where("contentId=$id")->delete();
			$supplyData['contentId']=$id;
			$supplyData['cId']=0;
			$supplyData['isAllChannel']=1;
			$supplyMicontent->add($supplyData);
		}
		if($resultPro!==false && $resultBase!==false && $resultMeter!==false) {
			$MicontentModel->commit();
			Output::instance()->resultCode();
		} else {
			$MicontentModel->rollback();
			Output::instance()->resultCode(code_sql_error);
		}
	}
	//批量复制
	public function copyContents($ids,$cid=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$ids = explode(",",$ids);
		foreach($ids as $key=>$value){
			self::copyContent($value,$cid);
		}
		Output::instance()->resultCode();
	}

	//跨平台复制
	public function copyContent($id,$cid=null){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId=Session::$user['customerId'];
		!$cid?$cid=$customerId:"";
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		$ContentTagModel = M("micontent_tag");
		$ContentTagListModel = M("micontent_tag_list");
		$shareBaseModel=M("mishare");
		$shareMaterModel=M("mishare_material");
		Session::switchCustomer($customerId);
		$MicontentModel->startTrans();
		$contentInfo = $MicontentModel->where("id=$id")->find();
		$oldId= $contentInfo['id'];
		$tags = $contentInfo['tags'];
		$oldCid = $contentInfo['fromCustomerId'];
		$contentInfo['fromCustomerId']=$cid;
		unset($contentInfo['id']);
		unset($contentInfo['vId']);
		unset($contentInfo['tags']);
		$newId = $MicontentModel->add($contentInfo);
		if(!$newId){
			$MicontentModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		$shareWhere['module']=array("eq","micontent");
		$shareWhere['moduleId']=array("eq",$oldId);
		$shareWhere['deleted']=array("eq",0);
		$shareMaterInfo = $shareMaterModel->where($shareWhere)->find();
		$shareBaseData=array(
			"module" => "micontent" ,
			"moduleId" => $newId ,
			"shareCount" => 0 ,
			"viewCount" => 0 ,
			"praiseCount" => 0 ,
			"commentCount" => 0 ,
			"createTime"=> date("Y-m-d H:i:s"),
			"deleted" => 0
		);
		$resultBase=$shareBaseModel->add($shareBaseData);
		if($resultBase ) {
			unset($shareMaterInfo['id']);
			$shareMaterInfo["sId"]=$resultBase;
			$resultMeter=$shareMaterModel->add($shareMaterInfo);
			if(!$resultMeter){
				$MicontentModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return;
			}
		}else{
			$MicontentModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		if ($tags) {
			$arrTag = explode(",", $tags);
			foreach($arrTag as $key=>$value){
				$tagInfo = $ContentTagModel->where("id=$value and fromCustomerId = $oldCid")->find();
				$tagName = $tagInfo['tagName'];
				$selfTagInfo = $ContentTagModel->where("tagName='$tagName' and fromCustomerId = $cid")->find();
				if($tagInfo){
					if(!$selfTagInfo){
						$tagData['fromCustomerId']=$cid;
						$tagData['tagName']=$tagName;
						$tagData['tagtplid']=1;
						$tagId = $ContentTagModel->add($tagData);
					}else{
						$tagId = $selfTagInfo['id'];
					}
				}
				$tagListData['fromCustomerId']=$cid;
				$tagListData['webPageId']=$newId;
				$tagListData['tagId']=$tagId;
				$ContentTagListModel->add($tagListData);
			}
			$newTags = $ContentTagListModel->where("fromCustomerId=$cid and webPageId=$newId")->field("group_concat(tagId) as tags")->find();
			$tagResult = $MicontentModel->where("id=$newId")->setField("tags",$newTags['tags']);
			if($tagResult===false){
				$MicontentModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return;
			}
		}
		$MicontentModel->commit();
		return $newId;
	}

	/**
	 * [deleteContent 删除素材]
	 * @param  [type] $ids [素材id]
	 * @return [type]      [description]
	 */
	public function delete($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		$ShareModel = M("mishare");
		$MaterialModel = M("mishare_material");
		$McommentModel = M("mirecomment");
		$where['id'] = $id;
		$data['deleted'] = 1;
		$MicontentModel->startTrans();
		$result = $MicontentModel->where($where)->save($data);
		Session::switchCustomer($cid);
		if ($result) {
			$sharewhere['module'] = 'micontent';
			$sharewhere['moduleId'] = $id;
			$shareId = $ShareModel->where($sharewhere)->find();
			Log::write("shareId:" . $ShareModel->getlastSql());
			$mwhere['sId'] = $shareId['id'];
			$result = $ShareModel->where($sharewhere)->delete();
			Log::write("删除share:$result ". $ShareModel->getlastSql());
			if ($result === false) {
				$MicontentModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return false;
			}
			$result = $MaterialModel->where($mwhere)->delete();
			Log::write("删除Material:$result ". $MaterialModel->getlastSql());
			if ($result === false) {
				$MicontentModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return false;
			}
			$result = $McommentModel->where($mwhere)->delete();
			Log::write("删除comment:$result ". $McommentModel->getlastSql());
			if ($result === false) {
				$MicontentModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return false;
			}else{
				$MicontentModel->commit();
				Output::instance()->resultCode(code_success);
			}

		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}

	//根据模板id获取单个标签模版信息
	public function miGetWebPageTagTemplateById($id) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$tempModel = M("pb_template");
		Session::switchCustomer($cid);
		$res = $tempModel ->where("id=$id")->find();
		//echo $tempModel->getLastSql();
		if ($res!==false) {
			Output::instance()->object($res);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	//获取素材标签模版列表
	public function miGetWebPageTagTemplateList($module = 'mi_content'){
		$retVal = Session::init();
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$tplModel = M("pb_template");
		Session::switchCustomer($cid);
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$where['module']=$module;
		$arr = $tplModel->where($where)->select();
		if ($arr) {
			Output::instance()->objArray($arr);
		} else {
			Output::instance()->resultCode();
		}
	}
	public function updateMiContentProductTags($mId,$pIds){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$mpModel = M("micontent_product_list");
		$success = true;
		if(!empty($pIds)){
			$pIds = explode(',',$pIds);
			$mpModel->where(['mcId' => $mId])->delete();
			foreach ($pIds as $pId){
				$data['mcId']=$mId;
				$data['pId']=$pId;
				$data['fromCustomerId']=$customerId;
				$success =$mpModel->add($data);
			}
		}else{
			$data['mcId']=$mId;
			$data['fromCustomerId']=$customerId;
			$success = $mpModel->where($data)->delete();
		}
		Session::switchCustomer($customerId);
		if($success){
			Output::instance()->resultCode(code_success);
		}
	}
	public  function  deleteMiContentPruduct($mId,$pId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$uModel = M("micontent_product_list");
		$condition['mcId']=array('eq',$mId);
		$condition['pId']=array('eq',$pId);
		$condition['fromCustormerId']=array('eq',$customerId);
		$result=$uModel->where($condition)->delete();
		if($result){
			Output::instance()->resultCode(code_success);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
		Session::switchCustomer($customerId);
	}
	public function getProductByMiContentId($mId){
		$retVal = Session::init();
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$uModel = M("micontent_product_list");
		Session::switchCustomer($cid);
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$where['mcId']=$mId;
		$arr = $uModel->alias('a')
			->join("inner join wx_module_product b on a.pId=b.id")
			->field("a.*,a.mcId as mId,b.name,b.id as pId,b.fixedPrice as price")
			->where($where)->select();
		if ($arr) {
			$count = $uModel->alias('a')
				->join("inner join wx_module_product b on a.pId=b.id")
				->field("a.*,b.name,b.id as pId,b.fixedPrice as price")
				->where($where)
				->count();
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode();
		}
	}


	/*以下为joymap新平台接口-------------------------------*/

	/**
	 * 获取文章列表
	 * @param null $title 标题
	 * @param null $group 分组
	 * @param null $public 0代表公共素材库,1代表个人素材库
	 * @param int $start 分页偏移量
	 * @param int $limit 查询条数
	 * @param string $order 排序
	 * @param string $by 排序字段
	 */
	public static function getNewContentList($title=NUll,$group=0,$public=0,$start=0,$limit=10,$order='desc',$by='createTime'){
		$relVal = Session::init();
		if(!$relVal){
			Output::instance()->object(code_access_denied);
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miContentTagList_table = M('micontent_tag_list');
		$miContent_table = M('micontent');
		$Model_IndMediaInfo = M('ind_media_info');
		$Order_table = M('module_product_order');
		Session::switchCustomer($cid);
		if (!empty($title)) {
			$map['mcont.title'] = array('like', "%$title%");
			$map['form.formName'] = array('like', "%$title%");
			$map['r.name'] = array('like', "%$title%");
			$map['_logic'] = "OR";
			$where["_complex"] = $map;
		}
		$where['mcont.deleted'] = 0;
		$where["mcont.type"]=array("EXP","=0 or mcont.type is null");

		if ($group) {
			//根据分组进行查询
			$where['tag.id'] = $group;
		}
		//$start=($start-1)*$limit;
		$where['mcont.fromCustomerId'] = array('eq', $cid);
		if($public == 0){
			//公共素材库,老平台的公共文章数据查询出来
			$where['mcont.public'] = 0;
//			$where['s.module'] = 'micontent';
		}else{
			//用户
			$where['mcont.cuId'] = Session::$user['id'];
			$where['mcont.public'] = 1;
//			$where['s.module'] = 'micontent';
		}

		$arr = $miContent_table->alias('mcont')
			->join("LEFT JOIN  wx_micontent_tag_list as tagl ON tagl.webPageId = mcont.id")
			->join("LEFT JOIN  wx_micontent_tag as tag ON tagl.tagId = tag.id")
			->join("wx_mishare sta on mcont.id=sta.moduleId and sta.module='micontent'")
			->join("wx_form as form On mcont.formId=form.id")
			->join("wx_micontent_product_list as product On mcont.id=product.mcId")
			->join('wx_share_reward r on r.id=mcont.rewardId')
			->join('wx_module_point_scheme s on s.id=mcont.pointSchemeId')
			->where($where)
			->limit($start,$limit)
			->field("mcont.*,GROUP_CONCAT(tag.tagName) as tagNames,GROUP_CONCAT(tag.id) AS tagIds,sta.viewUv,sta.shareCount,
			form.formName,GROUP_CONCAT(product.pId) as pId, r.name as rewardName, s.name as pointSchemeName")
			->order('mcont.'.$by.' '.$order)
			->group("mcont.id")
			->select();
		if ($arr) {
			$count =  $miContent_table->alias('mcont')->where($where)->count();
			$newArr = [];
			$APPID = $Model_IndMediaInfo->where(['cid' => $cid, 'isDefault' => 1])->getField('appid');
			$mediaInfo = $Model_IndMediaInfo->alias('a')->where(['a.cid' => $cid, 'a.isDefault' => 1])->join('inner join wx_customer_weixin_profile as b on a.id=b.mediaId')->find();
			if($mediaInfo['mode'] == 1){
				$url ='http://' . $APPID . '.'.C('NEWSERVER_HOST');
			}else{
				$url =C('SERVER_HOST');
			}
			foreach($arr as $key=>$val){
				if($val['ossLink']){
					$val['content'] = file_get_contents($val['ossLink']);
				}
				$val['formOrderCount'] = $Order_table->where(['moduleId' => $val['id'], 'status' => ['in', 'ok,delivering,refundedpart,submission']])->count();
//				$val['link'] = C('SERVER_HOST') . "call.html?customerId=" . $cid . "&module=micontent&method=getMiContentDetail&params=%7B%22id%22%3A%22". $val['id'] ."%22%7D";
				$val['link'] = $url."call.html?customerId=" . $cid . "&module=micontent&method=getMiContentDetail&params=%7B%22id%22%3A%22". $val['id'] ."%22%7D";
				$tagInfo = $miContentTagList_table->alias('a')->where(['webPageId' => $val['id']])->join('wx_micontent_tag as b On a.tagId=b.id')->field('GROUP_CONCAT(b.tagName) as tagNames,GROUP_CONCAT(b.id) AS tagIds')->find();
				$val['tagNames'] = $tagInfo['tagNames'];
				$val['tagIds'] = $tagInfo['tagIds'];
				$newArr[$key] = $val;
			}
			Output::instance()->objArray($newArr,$count);
		}else{
			//Output::instance()->resultCode(code_success);
			Output::instance()->object([
				'code'=>-1,
				'total'=>0,
				'results'=>[]
			]);
		}
	}
	public function getH5ServerHost(){
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$Model_IndMediaInfo = M('ind_media_info');
		Session::switchCustomer($cid);

		//获取平台默认公众号信息
		$mediaInfo = $Model_IndMediaInfo->where(['cid' => $cid, 'isDefault' => 1])->field('appid,mode')->find();
		if($mediaInfo['mode'] == 1){
			$url ='http://' . $mediaInfo['appid'] . '.'.C('NEWSERVER_HOST');
		}else{
			$url =C('SERVER_HOST');
		}
		return $url;
	}

	/**
	 * 文章关联商品
	 * @param $mId	文章id
	 * @param $pIds 商品id
	 */
	public function miContentProduct($mId,$pIds){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$mpModel = M("micontent_product_list");
		Session::switchCustomer($customerId);

		$pIds = explode(',',$pIds);
		$mpModel->where(['mcId' => $mId, 'fromCustomerId' => $customerId])->delete();
		foreach ($pIds as $k=>$pId){
			$data[$k]['mcId']=$mId;
			$data[$k]['pId']=$pId;
			$data[$k]['fromCustomerId']=$customerId;
		}
		$result = $mpModel->addAll($data);
		if($result){
			Output::instance()->resultCode(code_success);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}


	/**
	 * 获取分组信息
	 * @param int $public 0代表公共素材库,1代表个人素材库
	 * @param string $order
	 * @param string $orderBy
	 * @param int $start
	 * @param int $limit
	 * @param int $isAll
	 */
	public function miNewGetTag($public,$order = "number", $orderBy ="asc", $start = 0, $limit = 25,$isAll=1){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$TagModel = M("micontent_tag");
		Session::switchCustomer($cid);
		$where['t.fromCustomerId']=array("eq",$cid);
		if($public == 0){
			//公共素材库
			$where['t.fromUserId'] = 0;
		}else{
			//用户
			$where['t.fromUserId'] = Session::$user['id'];
		}
		if($isAll){
			$arr = $TagModel->alias('t')
				->field('t.*, count(l.webPageId) as contentCount')
				->join('left join wx_micontent_tag_list l on t.id=l.tagId')
				->where($where)
				->order("$order $orderBy")
				->group("t.id")
				->select();
		}else{
			$arr = $TagModel->alias('t')
				->field('t.*, count(l.webPageId) as contentCount')
				->join('left join wx_micontent_tag_list l on t.id=l.tagId')
				->where($where)
				->order("$order $orderBy")
				->limit("$start, $limit")
				->group("t.id")
				->select();
		}
		if ($arr) {
			$count = $TagModel->where($where)->count();
			Output::instance()->objArray($arr, $count);
		} else {
			Output::instance()->resultCode(code_success);
		}

	}

	/**
	 * 新增分组,老平台分组和分类标签是一个意思
	 * @param $tagName /分组名称
	 * @param $public 0代表公共素材库,1代表个人素材库
	 * @param int $number /编号,默认为0,新平台使用不到
	 * @param int $userUpload /以前没备注
	 * @param int $tplid /模板id
	 * @param string $picUrl /图片
	 * @param string $description /描述
	 */
	public function miNewAddTag($tagName,$public,$number=0,$userUpload=0,$tplid=1,$picUrl='',$description=''){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$WebpageTagModel = M("micontent_tag");
		Session::switchCustomer($cid);
		$where['fromCustomerId']=$cid;

		if($public == 0){
			$where['fromUserId'] = 0;
		}else{
			$where['fromUserId']=Session::$user['id'];
		}
		//已存在
		$where['tagName'] = $tagName;
		$webpagetag = $WebpageTagModel->where($where)->find();
		if($webpagetag){
			Output::instance()->resultCode(code_webpage_add_tag_exist);
			return;
		}
		$add['fromCustomerId']=$cid;

		/*新增*/
		if($public == 0){
			$add['fromUserId'] = 0;
		}else{
			$add['fromUserId']=Session::$user['id'];
		}

		$add['tagName'] = $tagName;
		$add['number']=$number;
		$add['userUpload']=$userUpload;
		$add['picUrl']=$picUrl;
		$add['description']=$description;
		$add['tagtplid']=$tplid;
		$addTag = $WebpageTagModel->add($add);
		R('Log/add',array('material','145','素材管理',op_add,$WebpageTagModel->getLastSql(),'新增一个文章组'));
		$out=new StdClass();
		$out->code=0;
		$out->id=$addTag;
		if ($addTag) {
			Output::instance()->object($out);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}

	}

	/**
	 * 文章移动分组
	 * @param $ids /文章id数组
	 * @param $tagId /组id
	 */
	public function contentMovieGroup($ids,$tagId){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->object(code_access_denied);
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$contentTag_table = M('micontent_tag_list');
		$content_table = M('micontent');
		Session::switchCustomer($cid);

		$ids = json_decode($ids);

		$map = $add =  [];
		$map['fromCustomerId'] = $cid;
		$add['fromCustomerId'] = $cid;
		$map['tagId'] = $tagId;
		$add['tagId'] = $tagId;
		foreach($ids as $k=>$val){
			$map['webPageId'] = $val;
			$contentTagRet = $contentTag_table->where($map)->find();
			if($contentTagRet){
				continue;
			}

			//保存关联表
			$add['webPageId'] = $val;
			$addResult = $contentTag_table->add($add);
			if(!$addResult){
				Output::instance()->resultCode(code_sql_error);
				return;
			}
			//保存内容表tags
			$tagsField = $content_table->where(array('id'=>$val))->getField('tags');
			if($tagsField){
				$newTags = $tagId.','.$tagsField;
			}else{
				$newTags = $tagId;
			}
			$updateRet = $content_table->where(array('id'=>$val))->save(array('tags'=>$newTags));
			R('Log/add',array('material','145','素材管理',op_update,$content_table->getLastSql(),'素材管理中文章移动分组'));
			if(!$updateRet){
				Output::instance()->resultCode(code_sql_error);
				return;
			}
		}
		Output::instance()->resultCode();

	}

	/**
	 * 删除文章组
	 * @param $tagId /组id
	 */
	public function delTag($tagId){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->object(code_access_denied);
		}

		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$contentTag_table = M('micontent_tag_list');
		$content_table = M('micontent');
		$conTag_table = M('micontent_tag');
		Session::switchCustomer($cid);

		//删除content_tag表记录
		$delRet = $conTag_table->where(array('id'=>$tagId))->delete();
		R('Log/add',array('material','145','素材管理',op_delete,$conTag_table->getLastSql(),'素材管理中删除一个文章组'));
		if(!$delRet){
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		//删除关联
		$delRelationRet = $contentTag_table->where(array('tagId'=>$tagId, 'fromCustomerId'=>$cid))->delete();
		R('Log/add',array('material','145','素材管理',op_delete,$contentTag_table->getLastSql(),'素材管理删除组与文章关联信息'));
		if(!$delRelationRet){
			Output::instance()->resultCode(code_sql_error);
		}
		Output::instance()->resultCode();
	}

	/**
	 * 新增文章和保存文章
	 * @param null $id
	 * @param int $public 0代表公共素材库,1代表个人素材库
	 * @param null $vId 供应商id
	 * @param string $title 内容标题
	 * @param null $writer 作者
	 * @param int $tplId 关联文章模板表中的id 线上表不能为null,默认值为1
	 * @param null $picUrl 封面图
	 * @param string $picUrl1 封面图组合
	 * @param null $recomment 小编推荐
	 * @param null $content 内容,新的保存到oss
	 * @param null $ossLink oss链接,保存正文内容
	 * @param null $tags 分组
	 * @param null $focusLink 跳转关注链接
	 * @param int $isRecommend 是否推荐,线上表不能为null
	 * @param null $accessTag 阅读者打标签
	 * @param null $shareImgs 分享图片,上传的分享图片的第一张
	 * @param null $shareImgs1 分享图片集合
	 * @param null $description 分享描述
	 * @param null $publishTime 发布日期
	 * @param null $associatedShop 关联店铺
	 * @param int $type  类型 0：内容 1：帖子 2：广告
	 * @param null $channels
	 * @param int $isAllChannel
	 * @param int $retype
	 * @param int $wordNum
	 * @param int $qid  关联的圈id
	 * @param int $icoFont 圈图标文字
	 * @param int $pointSchemeId  关联的积分方案id,0代表取消,大于0关联
	 * @param int $jumpMode 提交表单后的跳转方式 0 默认 1 跳转url 2 跳转成功页并展示图片
	 * @param int $jumpUrl  提交表单后的跳转的url地址
	 * @param int $bigPicUrl  封面大图
	 * @return object
	 */
	public static function saveNewContent($id=NULL,$public=0,$vId=NULL, $title='',$writer=NULL,$tplId=5, $picUrl=NULL,
                                          $picUrl1="",$recomment=NULL,$content=NULL,$ossLink=NULL,$tags=NULL, $focusLink=NULL,
                                          $isRecommend=0,$accessTag=NULL,$shareImgs=NULL,$shareImgs1=NULL,$description=NUll,
                                          $publishTime=NULL,$associatedShop=NULL,$type=0,$channels=NULL,$isAllChannel=0,
										  $retype=1,$wordNum=0,$qid=0,$icoFont=NULL,$shareTitle='',$pointSchemeId=-1,$jumpMode=0,
										  $jumpUrl=null,$bigPicUrl=null){
		if($retype==1){
			$retVal = Session::init();
			if (!$retVal) {
				Output::instance()->resultCode(code_access_denied);
				return;
			}
			if(!empty($accessTag)){
				addAccessTags($accessTag);
			}
		}

		$pid = $id;
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		//组与文章关联表
		$ContentTagListModel = M("micontent_tag_list");
		//分享基础表
		$shareBaseModel=M("mishare");
		//分享素材表
		$shareMaterModel=M("mishare_material");
		//内容投放渠道表
		$supplyMicontent = M("module_supply_chain_content");

		if($id && ($pointSchemeId >= 0)){
			$relationRet = $MicontentModel->where("id=$id")->save(['pointSchemeId' => $pointSchemeId]);
			if(!is_numeric($relationRet)){
				Log::write('文章关联积分方案失败:'.$MicontentModel->getDbError());
				Output::instance()->object([
					'code' => -1,
					'msg' => '保存失败',
					'results' => []
				]);
				return;
			}
			Output::instance()->object([
				'code' => 0,
				'msg' => '保存成功',
				'results' => []
			]);
			return;
		}

		$time = date("Y-m-d H:i:s");
		$data["fromCustomerId"] = $cid;
		$data["vId"] = $vId;
		$data["title"] = $title?$title:'新建文章';
		$data["writer"] = $writer;
		$data["picUrl"] = $picUrl;
		$data["picUrl1"]=$picUrl1;
		$data["recomment"]=$recomment;
		$data["isRecommend"]=$isRecommend;
		$data["content"]=$content;
		$data["accessTag"] = $accessTag;
		$data["tags"] = $tags;
		$data["ossLink"] = $ossLink;
		$data["tplid"] = $tplId;
		$data["focusLink"] = $focusLink;
		$data["description"] = $description;
		$data["createTime"] = $time;
		$data["updateTime"] = $time;
		$data["associatedShop"]=$associatedShop;
		$data["publishTime"] = $publishTime;
		$data["type"] = $type;
		$data["cuId"] = Session::$user['id'];
		$data["qid"] = $qid;
		$data["quanIcoFont"] = $icoFont;
		$data["jumpMode"] = $jumpMode;
		$data["jumpUrl"] = $jumpUrl;
		$data["bigPicUrl"] = $bigPicUrl;
//		$data["formId"] = $formId;

		/*新增一个字段*/
		if($public == 0){
			//公共素材库
			$data["public"] = 0;
		}else{
			$data["public"] = 1;
		}
		/*新增统计字数的字段*/
		if(!$content){
			$data['wordNum'] = 0;
		}else{
			$str = htmlspecialchars_decode($content);
			$str = preg_replace('/[\x80-\xff]{1,3}/', ' ', $str,-1, $num);
			$num += str_word_count($str);
			$data['wordNum'] = $num;
		}
		if($retype==2){
			$data['wordNum'] =$wordNum;
		}

		if($publishTime==null){
			$data["publishTime"] = $time;
		}
		$MicontentModel->startTrans();
		if($id) {
			$resultPro = $MicontentModel->where("id=$id")->save($data);
			R('Log/add',array('material','145','素材管理',op_update,$MicontentModel->getLastSql(),'修改更新文章内容'));
		} else{
			$resultPro = $MicontentModel->add($data);
			R('Log/add',array('material','145','素材管理',op_add,$MicontentModel->getLastSql(),'新增一篇文章'));
			$id=$resultPro;
		}

		/*if($module == 1){
			//gaogao直接返回
			if($resultPro !== false) {
				$MicontentModel->commit();
				Output::instance()->resultCode();
			} else {
				$MicontentModel->rollback();
				Output::instance()->resultCode(code_sql_error);
			}
			return;
		}*/

		//生成一条文章在分享基础表中增加一条记录
		$shareBaseData=array(
			"module" => "micontent" ,
			"moduleId" => $id ,
			"shareCount" => 0 ,
			"viewCount" => 0 ,
			"praiseCount" => 0 ,
			"commentCount" => 0 ,
			"createTime"=> $time,
			"deleted" => 0
		);
		//分享素材表
		$shareMaterData=array(
			"title" => $shareTitle,
			"shareImg" => $shareImgs,
			"shareImg1" => $shareImgs1,
			"description" => $description,
			"deleted"=>0
		);
		$shareBaseWhere["module"]="micontent";
		$shareBaseWhere["moduleId"]=$id;
		if($pid) {
			//分享基础表中将此更新的文章分享总数等记录归零
			//$resultBase=$shareBaseModel->where($shareBaseWhere)->save($shareBaseData); //改为无需重置为0 2017-7-24
			//R('Log/add',array('material','145','素材管理',op_update,$shareBaseModel->getLastSql(),'修改更新文章的分享详情'));
			$resultBaseList=$shareBaseModel->where($shareBaseWhere)->find();

			if($resultBaseList) {
				//修改分享素材表中对应的素材更新
				$baseId=$resultBaseList["id"];
				$resultMeter=$shareMaterModel->where('sId=' . $baseId)->save($shareMaterData);
				//R('Log/add',array('material','145','素材管理',op_update,$shareMaterModel->getLastSql(),'修改更新文章的分享素材'));
			}
		} else {
			//添加一条记录
			$resultBase=$shareBaseModel->add($shareBaseData);
			//R('Log/add',array('material','145','素材管理',op_add,$shareBaseModel->getLastSql(),'新增一篇文章的保存基础分享详情'));
			//同时添加一条素材表记录
			if($resultBase) {
				$shareMaterData["sId"]=$resultBase;
				$resultMeter=$shareMaterModel->add($shareMaterData);
				//R('Log/add',array('material','145','素材管理',op_add,$shareBaseModel->getLastSql(),'新增文章保存分享素材'));
			}
		}
		Session::switchCustomer($cid);
		if ($resultPro) {
			//保存文章和分组的关联信息
			$arrTag = explode(",", $tags);
			//将之前的关系全部删除掉再次保存
			$ContentTagListModel->where("webPageId=$id")->delete();
			R('Log/add',array('material','145','素材管理',op_delete,$ContentTagListModel->getLastSql(),'删除文章之前与分组的关系重新保存'));
			if($tags != ''){
				foreach ($arrTag as $tagId) {
					$dataTagList["tagId"] = $tagId;
					$dataTagList["webPageId"] = $id;
					$dataTagList["fromCustomerId"] = $cid;
					$ContentTagListModel->add($dataTagList);
					R('Log/add',array('material','145','素材管理',op_add,$ContentTagListModel->getLastSql(),'保存文章与组的关联'));
				}
			}
		}
		if($channels){
			$channels=explode(",",$channels);
			$supplyMicontent->where("contentId=$id")->delete();
			foreach($channels as $key=>$value){
				$supplyData['contentId']=$id;
				$supplyData['cId']=$value;
				$supplyData['isAllChannel']=0;
				$supplyMicontent->add($supplyData);
			}
		}
		if($isAllChannel){
			$supplyMicontent->where("contentId=$id")->delete();
			$supplyData['contentId']=$id;
			$supplyData['cId']=0;
			$supplyData['isAllChannel']=1;
			$supplyMicontent->add($supplyData);
		}
		if($resultPro!==false && $resultMeter!==false) {
			$MicontentModel->commit();
			if($retype==1){
				$retrun['code']=0;
				$retrun['msg']='ok';
				$retrun['id']=$id;
				Output::instance()->object($retrun);
			}else{
				return  $id;
			}
		} else {
			$MicontentModel->rollback();
			Output::instance()->resultCode(code_sql_error);
		}
	}


	/**
	 * 将文章上传到素材库或同步我的素材库
	 * @param array $contentId /文章id数组
	 * @param $public /0:上传到我的素材,1:上传到公共素材库
	 */
	public static function editMaterialLibrary($contentId,$public){
		$relVal = Session::init();
		if(!$relVal){
			Output::instance()->object(code_access_denied);
		}

		//获取的id数组所对应的文章信息,保存起来,暂不考虑重复问题
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miContent_table = M('micontent');
		//分享基础表
		$shareBaseModel = M("mishare");
		//分享素材表
		$shareMaterModel = M("mishare_material");
		Session::switchCustomer($cid);
		$idsArr = explode(',', $contentId);
		if(count($idsArr)<0){
			Output::instance()->object(array(
				'code'=>-1,
				'msg'=>'导入的素材为空',
				'data'=>'',
			));
			return;
		}

		$userId = Session::$user['id'];
		//$map['fromCustomerId'] = $cid;
		//查询出对应文章信息
		foreach($idsArr as $key=>$value){
			$map['id'] = $value;
			$result = $miContent_table->where($map)->find();
			if($result == null){
				continue;
			}
			if($public) {
				//同步公共素材库
				$result['public'] = 0;
			}else{
				//同步到我的
				$result['public'] = 1;
			}
			$result['cuId'] = $userId;
			$result['createTime'] = date('Y-m-d H:i:s');
			$result['publishTime'] = date('Y-m-d H:i:s');
			$result['updateTime'] = date('Y-m-d H:i:s');
			unset($result['id']);
			$miContent_table->startTrans();
			$contentId = $miContent_table->add($result);
			R('Log/add',array('material','145','素材管理',op_add,$miContent_table->getLastSql(),'将文章素材同步到公共素材库或者个人素材库'));
			if($contentId){
				/*需保存分享基础表和分享素材表*/
				$shareBaseResult = $shareBaseModel->where(array('moduleId'=>$value,'module'=>'micontent'))->find();
				$oldSId = $shareBaseResult['id'];
				if($shareBaseResult){
					$shareBaseData=array(
						"module" => "micontent" ,
						"moduleId" => $contentId ,
						"shareCount" => 0 ,
						"viewCount" => 0 ,
						"praiseCount" => 0 ,
						"commentCount" => 0 ,
						"createTime"=> date('Y-m-d H:i:s'),
						"deleted" => 0
					);
					$sId = $shareBaseModel->add($shareBaseData);
					//R('Log/add',array('material','145','素材管理',op_add,$shareBaseModel->getLastSql(),'同步文章素材后同步生成基础分享详情'));
					if($sId){
						//保存分享素材表
						$shareMaterial = $shareMaterModel->where(array('sId'=>$oldSId))->find();
						/*echo '<pre>';
						var_dump();
						echo '<pre>';exit;*/
						$shareMaterial['sId'] = $sId;
						unset($shareMaterial['id']);
						$materialId = $shareMaterModel->add($shareMaterial);
						//R('Log/add',array('material','145','素材管理',op_add,$shareBaseModel->getLastSql(),'同步素材后同时同步分享素材(新平台)'));
						if(!$materialId){
							$miContent_table->rollback();
							Output::instance()->object([
								'code'=>-1,
								'msg'=>'保存素材失败',
								'data'=>'',
							]);
						}
					}
				}
			}
			$miContent_table->commit();
		}

		if($materialId){
			Output::instance()->object([
				'code'=>0,
				'msg'=>'提交成功',
				'data'=>'',
			]);
			return;
		}
		Output::instance()->object(code_access_denied);
	}

	/**
	 * 删除内容
	 * @param $contentId /内容ids,多个以逗号分隔
	 * @return object
	 */
	public static function delNewContent($contentId,$retype=1, $op = 1){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$MicontentModel = M("micontent");
		$ShareModel = M("mishare");
		$MaterialModel = M("mishare_material");
		//$McommentModel = M("mirecomment");
		$where['id'] = array('in', $contentId);
        if ($op == 1)
		    $MicontentModel->startTrans();
		$result = $MicontentModel->where($where)->setField('deleted', $op);
        if ($op == 0)
            return 1;
		R('Log/add',array('material','145','素材管理',op_delete,$MicontentModel->getLastSql(),'删除所选中的文章素材'));
		Session::switchCustomer($cid);
		if ($result) {
			$contentIdArr = explode(',', $contentId);
			foreach($contentIdArr as $key=>$val){
				$sharewhere['module'] = 'micontent';
				$sharewhere['moduleId'] = $val;
				$shareId = $ShareModel->where($sharewhere)->find();
				$mwhere['sId'] = $shareId['id'];
				//删除文章在分享基础表中的数据
				$result = $ShareModel->where($sharewhere)->delete();
				//R('Log/add',array('material','145','素材管理',op_delete,$MicontentModel->getLastSql(),'删除内容对应的分享记录(新平台)'));
				if ($result === false) {
					$MicontentModel->rollback();
					Output::instance()->resultCode(code_sql_error);
					return false;
				}
				//删除文章在分享素材表中的数据
				$result = $MaterialModel->where($mwhere)->delete();
				//R('Log/add',array('material','145','素材管理',op_delete,$MicontentModel->getLastSql(),'删除内容的分享素材(新平台)'));
				if ($result === false) {
					$MicontentModel->rollback();
					Output::instance()->resultCode(code_sql_error);
					return false;
				}
			}
			/*//删除密友商品表中某一个圈的分享记录,由于暂不考虑此记录,暂且注释
			$result = $McommentModel->where($mwhere)->delete();
			Log::write("删除comment:$result ". $McommentModel->getlastSql());
			if ($result === false) {
				$MicontentModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return false;
			}else{
				$MicontentModel->commit();
				Output::instance()->resultCode(code_success);
			}*/
			$MicontentModel->commit();
			if($retype==1)
				Output::instance()->resultCode(code_success);
			else
				return 1;
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}

	//save更新保存的时候需要将字段tags保存起来(用于编辑页的显示),同时分组关联需要保存起来(用户分组筛选显示)


	/**
	 * 保存文章审核状态以及发送站内消息
	 * @param int $contentId 文章ID
	 * @param int $mediaId 媒体ID
	 * @param int $reviewer 审核人ID
	 * @param int $massId  群发ID
	 * @return array $return 返回错误码和返回信息
	 */

	public function submitContentMassReview($contentId,$mediaId,$reviewer,$massId)
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		/**2.数据表模型*/
		$userId = Session::$user['id'];
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$user = M('customer_user');
		Session::switchCustomer($customerId);
		$review = M('mass_review');

		//判断是不是编辑身份
		 if (!Session::isEdit()){
            $return['code'] = 1;
            $return['msg'] = '您无此权限,请联系运营管理员';
            $return['data'] = '';
            return $return;
        }
		/**3.发送站内消息,添加审核信息*/
		$userInfo = $user->field("fullName")->where("id=$reviewer")->find();
		$review->create();
		$review->contentId = $contentId;
		$review->mediaId = $mediaId;
		$review->userId = $userId;
		$review->reviewer = $reviewer;
		$review->createTime = date('Y-m-d H:i:s');
		$review->status = 1;
		$review->massId = $massId;
		$review->type= 2;
		$reviewId =$review->add();
        $review_sql = $review->getLastSql();
        R('Log/add',array('review','141','审核',op_add,$review_sql,'向'.$userInfo['fullName'].'提交文章审核'));
		$data = PlatMessageAction::pushMessage('文章群发审核',Session::$user['fullName'].'提交头条群发前的文章审核',array($reviewer),$userId,0,'review','审核',1, 1);
		if ($reviewId){
			$return['code'] = 0;
			$return['msg'] = 'ok';
		}else{
			$return['code'] = 1;
			$return['msg'] = '审核信息添加失败请重试';
		}
		return $return;

	}

	/**
	 * 保存文章撤回状态
	 * @param int $reviewId 审核ID
	 * @return $return 返回错误码和返回信息
	 */
	public function recallContentReview($reviewId)
	{
		//将已经撤回的状态位的信息改为代表撤回的数字。
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/**2.数据表模型*/
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$content = M('micontent');
		$user = M('customer_user');
		Session::switchCustomer($customerId);
		$review = M('mass_review');
		$mass = M('module_mass_havesend');

		//判断是不是编辑身份
		 if (!Session::isEdit()){
            $return['code'] = 1;
            $return['msg'] = '您无此权限,请联系运营管理员';
            $return['data'] = '';
            Output::instance()->object($return);
            return;
        }
		/**3.修改审核表的审核状态*/
		$contentInfo = $review->field('contentId,reviewer,massId')->where("id=$reviewId")->find();
		$data_mass['status'] = 4;
		$data_mass['updateTime'] = date("Y-m-d H:i:s");
		$mass_result = $mass->where("id=".$contentInfo['massId'])->save($data_mass);
		if ($mass_result !== false){
			$data_review['status'] = 4;
			$data_review['updateTime'] = date('Y-m-d H:i:s');
			$result_review = $review->where("id=$reviewId")->save($data_review);
			if ($result_review !== false){
			    $data_content['lockTime'] = date("Y-m-d H:i:s");
			    $result_content = $content->where("id=".$contentInfo['contentId'])->save($data_content);
			    $reviewInfo = $user->field("fullName")->where("id=".$contentInfo['reviewer'])->find();
                $content_sql = $content->getLastSql();
                R('Log/add',array('review','141','审核',op_update,$content_sql,'将已送审到'.$reviewInfo['fullName'].'的文章撤回'));
			    if ($result_content !== false){
                    $return['code'] = 0;
                    $return['msg'] = 'ok';
                    Output::instance()->object($return);
                }else{
                    $return['code'] = 1;
                    $return['msg'] = '文章锁定状态修改失败';
                    Output::instance()->object($return);
                }

			}else{
				$return['code'] = 1;
				$return['msg'] = '文章撤回状态修改失败，请重试';
				Output::instance()->object($return);
			}
		}else{
			$return['code'] = 1;
			$return['msg'] = '群发文章撤回状态修改失败，请重试';
			Output::instance()->object($return);
		}



	}


	/**
	 * 保存文章相关审核状态
	 * @param int $result  审核结果（通过为1，不通过为0）
	 * @param string $reviewOpinion 审核意见
	 * @param int $reviewId  审核ID
	 * @return array $return  返回错误码和返回信息
	 */
	public function handleContentReview($result,$reviewOpinion='',$reviewId)
	{
		/**1.判断用户是否登录*/
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/**2.数据表模型*/
		$userId = Session::$user['id'];
		$customerId = Session::$user['customerId'];

		Session::switchCustomer(0);
		$user = M('customer_user');
		Session::switchCustomer($customerId);
		$review = M('mass_review');
		$mass = M('module_mass_havesend');

		/**3.数据整理*/
		//取得审核基本信息
		$reviewInfo = $review->field('contentId,massId,status,userId,mediaId')->where("id=$reviewId")->find();
		$editId = $reviewInfo['userId'];
		$editInfo = $user->field("fullName")->where("id=$editId")->find();

		//根据用户审核意见处理不同逻辑
		if ($result){
			//判断用户审核是否被撤回
			if ($reviewInfo['status'] !== '4'){
				//更改文章素材审核状态
				$data_review['status'] = 2;
				$data_review['reviewOpinion'] = $reviewOpinion;
				$data_review['updateTime'] = date('Y-m-d H:i:s');
				$result_review = $review->where("id=$reviewId")->save($data_review);
				//判断审核表信息是否添加成功
				if ($result_review !== false){
                    $review_sql = $review->getLastSql();
                    R('Log/add',array('review','141','审核',op_update,$review_sql,'通过'.$editInfo['fullName'].'的文章审核'));
					PlatMessageAction::pushMessage('文章过审','文章通过'.Session::$user['fullName'].'审核',array($reviewInfo['userId']),$userId,1,'review','审核',1, 1);
					R('Material/mass',array($reviewInfo['massId'],$reviewInfo['contentId'],$reviewInfo['mediaId']));
					$return['code'] = 0;
					$return['msg'] = '文章经过审核';
					Output::instance()->object($return);
				}else{
					$return['code'] = 1;
					$return['msg'] = '文章审核状态更改为通过失败,请重试';
					Output::instance()->object($return);
				}
			}else{
				$return['code'] = 1;
				$return['msg'] = '该文章用户已经撤回';
				Output::instance()->object($return);
			}
		}else{
			//判断用户是否已经撤回该文章
			if ($reviewInfo['status'] !== '4'){
				//更改文章审核状态
				$data['status'] = 3;
				$data['reviewOpinion'] = $reviewOpinion;
				$data['updateTime'] = date('Y-m-d H:i:s');
				$result = $review->where("id=$reviewId")->save($data);
				if ($result !== false){
					//发送站内消息通知审核状态
                    $review_sql = $review->getLastSql();
                    R('Log/add',array('review','141','审核',op_update,$review_sql,'驳回'.$editInfo['fullName'].'的文章审核'));
					PlatMessageAction::pushMessage('文章未过审','文章未经过'.Session::$user['fullName'].'审核，审核意见为：'.$reviewOpinion,array($reviewInfo['userId']),$userId,1,'review','审核',1, 1);
					$return['code'] = 0;
					$return['msg'] = '该文章未经过审核，请重新提交审核';
					Output::instance()->object($return);
				}else{
					$return['code'] = 1;
					$return['msg'] = '文章审核状态更改为未通过失败,请重试';
					Output::instance()->object($return);
				}
			}else{
				$return['code'] = 1;
				$return['msg'] = '该文章用户已经撤回';
				Output::instance()->object($return);
			}
		}
	}
	/**
	 * 获取头条发文的标签展示
	 */
	public function toutiaoTag()
	{
		/** 1. 判断是否登录 */
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 2. 数据表模型 */
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$tag = M('toutiao_article_tag');
		Session::switchCustomer($customerId);

		/**3.获取数据*/
		$tagInfo = $tag->field('id,tag')->select();

		$num = count($tagInfo);
		for ($i = 0;$i < $num;$i++){
			$tagArray[$tagInfo[$i]['id']] = $tagInfo[$i]['tag'];
		}

		$return['code'] = 0;
		$return['msg'] = $tagArray;
		Output::instance()->object($return);


	}

	/**
	 * 根据调取接口发送头条消息
	 * @param int $mediaId  自媒体账号id
	 * @param int $contentId  文章id
	 * @param int $article_tag  文章分类
	 */

	public function pushToutiaoContent($mediaId,$contentId,$article_tag)
	{
		/** 1. 判断是否登录 */
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 2. 数据表模型 */
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$media = M('ind_media_info');
		$article = M('micontent');
		$tag = M('toutiao_article_tag');
		Session::switchCustomer($customerId);

		/**3.获取数据*/
		$articleInfo = $article->field('title,description,ossLink')->where("id=$contentId")->find();
		$articleInfo['ossLink'] = file_get_contents($articleInfo['ossLink']);
		$tagInfo  = $tag->field('tagName')->where("id=$article_tag")->find();
		$result = ToutiaoApi::getToutiaoAccessToken($mediaId);
		/**3.进行文章发送*/
		if ($result['code'] == 0) {
			$mediaInfo = $media->field('accessToken,third_platform_appid')->where("id=$mediaId")->find();
			$data = ToutiaoApi::pushArticle($mediaInfo['accessToken'], $mediaInfo['third_platform_appid'], $articleInfo['title'], $articleInfo['ossLink'], $articleInfo['recomment'], 1, $tagInfo['tagName']);
			$media_sql = $media->getLastSql();
			 R('Log/add',array('material','145','素材管理',op_add,$media_sql,'进行头条号发文'));
			if ($data['message'] == 'error') {
				$return['code'] = 1;
				$return['msg'] = $data['data'];
			} else {
				$return['code'] = 0;
				$return['msg'] = '头条号文章发送成功';
			}
			return $return;
		} else {
			return $result;
		}
	}


    /**
     * 得到各种审核状态的所有文章
     * @param int $status 默认0所有，1未审核的文章、2审核通过的文章、3审核未通过的文章,
     * @param string $search 需要查询的标题
     * @param int $role  需要查询的角色1：审核人2：编辑,默认为1
     * @return array $return  返回错误码和返回信息
     */
    public function reviewContentList($status=0,$search ='',$role=1)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $media = M('ind_media_info');
        Session::switchCustomer($customerId);
        $review = M('mass_review');
        $where['reviewer'] = $userId;
        $where['deleted'] = array("NEQ",1);
        //$where['status'] = array("NEQ",4);
        $reviewer = $media->field('id')->where($where)->select();


        if ($reviewer && Session::isEdit()){
            if ($role == 1){
                $arr = R('MiContent/getReviewInfo',array($status,$search,$role));
                $return['code'] = 2;
                $return['msg'] = 1;  //1.审核人身份，2.编辑身份
                $return['data'] = $arr;
                Output::instance()->object($return);
                return;
            }else if ($role == 2){
                $arr = R('MiContent/getReviewInfo',array($status,$search,$role));
                $return['code'] = 2;
                $return['msg'] = 2;  //1.审核人身份，2.编辑身份
                $return['data'] = $arr;
                Output::instance()->object($return);
                return;
            }
        }

        if ($reviewer){
            //获取审核相关状态的所有文章  type：1.公众号，2：头条号
            $arr = R('MiContent/getReviewInfo',array($status,$search,1));
            $return['code'] = 0;
            $return['msg'] = 1;
            $return['data'] = $arr;
            Output::instance()->object($return);
        }else if (Session::isEdit()){
            $arr = R('MiContent/getReviewInfo',array($status,$search,2));
            $return['code'] = 0;
            $return['msg'] = 2;
            $return['data'] = $arr;
            Output::instance()->object($return);
        }else{
            $return['code'] = 1;
            $return['msg'] = '您无此权限,请联系运营管理员';
            $return['data'] = '';
            Output::instance()->object($return);
        }
    }

    /**
     * 得到具体文章信息
     * @param int $status 默认0所有，1未审核的文章、2审核通过的文章、3审核未通过的文章
     * @param string $search 需要查询的标题
     * @param int $role 需要查询的角色1：审核人2：编辑
     * @return array $return  返回错误码和返回信息
     */
    public function getReviewInfo($status=0,$search='',$role)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 2. 数据表模型 */
        $userId     = Session::$user['id'];
        $customerId = Session::$user['customerId'];
        Session::switchCustomer($customerId);
        $review  = M('mass_review');

        if ($role == 1){
            if ($status == 0){
                $where['reviewer'] = $userId;
                $where['type'] = 2;//获取审核相关状态的所有文章  type：1.公众号，2：头条号
            }else{
                $where['reviewer'] = $userId;
                $where['status'] = $status;
                $where['type'] = 2;//获取审核相关状态的所有文章  type：1.公众号，2：头条号
            }
        }else if ($role == 2){
            if ($status == 0){
                $where['userId'] = $userId;
                $where['type'] = 2;//获取审核相关状态的所有文章  type：1.公众号，2：头条号
            }else{
                $where['userId'] = $userId;
                $where['status'] = $status;
                $where['type'] = 2;//获取审核相关状态的所有文章  type：1.公众号，2：头条号
            }
        }

        $reviewInfo = $review->field('id,mediaId,massId,contentId')->where($where)->select();
        $num = count($reviewInfo);
        for ($i=0;$i<$num;$i++){
            $reviewId[]= $reviewInfo[$i]['id'];
        }
        if(!empty($search)) {
            $where_select['cont.title']= array("like","%".trim($search)."%");
        }

        $where_select['re.id']=array("in",$reviewId);
        $where_select['re.status']=array("NEQ",4);
        $where_select['cont.deleted']=array("NEQ",1);
        $arr = $review->alias('re')
            ->join("LEFT JOIN  wx_micontent as cont ON re.contentId = cont.id")
            ->join("LEFT JOIN  wx_customer_toutiao_profile as toutiao ON re.mediaId = toutiao.mediaId")
            ->join("LEFT JOIN  wx_".$customerId."_module_mass_havesend as mass ON re.massId =mass.id ")
            ->where($where_select)
            ->field("cont.*,toutiao.screen_name,toutiao.avatar_url,mass.sendtime,mass.sendType,re.id,re.massId,re.type,re.reviewOpinion,re.status")
            ->order('re.createTime desc')
            ->select();
        $review_sql = $review->getLastSql();
        R('Log/add',array('material','145','素材管理',op_find,$review_sql,'查看审核相关的所有文章'));
        return $arr;
    }

    /**
	* 群发素材备份
	* $materialId   备份的素材id
	* */
	public function miContentBackups($materialId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miContent=M('micontent');
		Session::switchCustomer($customerId);
		$msg=$miContent->where("id=$materialId")->select();;
		if($msg){
			$msg[0]['backups']=$msg[0]['id'];//备份的类型被区分
			unset($msg[0]['id']);
			$miContentId=$miContent->addAll($msg);//群发后留备份
		}
		return $miContentId;
	}

    /**
     * 获得文章素材的菜单
     *
     * @param $contentId  获得文章信息需要文章id, 所以这里url需要拼上
     */
    public function getMenuById($contentId)
    {

        // 菜单配置数组
        $data = [
            'group'     => '文章素材',
            'children'  => [
                [
                    'name'  => '编辑',
                    'url'   => '#/joymap/materialmanager/material/'.$contentId.'/content',
                ],
                [
                    'name'  => '群发',
                    'url'   => '#/joymap/materialmanager/material/'.$contentId.'/massSend',
                ]
            ]

        ];

        $index = 1;
        $arr_child = [];
        foreach ($data['children'] as $child_k => $child_v) {
            // 这个菜单是_胡英俊_给出的菜单树demo结构
            $m = [
                'id'        => $index,
                'name'      => $child_v['name'],
                'level'     => 1,
                'parent'    => 0,
                'path'      => "$index",
                'icon'      => '',
                'url'       => $child_v['url'],
                'isMenu'    => true,
                'children'  => []
            ];
            array_push($arr_child, $m);
            $index++;
        }

        $menu = [
            'id'        => 0,
            'group'     => $data['group'],
            'children'  => $arr_child
        ];


        Output::instance()->object(['data' => [$menu]]);
    }

	/**
	 * 保存表单和内容的关联
	 * @param $miContentId	/内容 id
	 * @param null $formId	/表单id
	 */
	public function saveMicontentForm($miContentId, $formId=null){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miContent_tab = M("micontent");
		Session::switchCustomer($cid);
		$result = $miContent_tab->where(['id'=>$miContentId])->save(['formId'=>intval($formId)]);
		if(!is_numeric($result)){
			Log::write('jie---123'.$miContent_tab->getLastSql());
			Output::instance()->object([
				'code'=>1,
				'msg'=>'保存失败',
				'results'=>[]
			]);
			return;
		}

		Output::instance()->object([
			'code'=>0,
			'msg'=>'ok',
			'results'=>[]
		]);
	}
	/**
	 * 保存内容与奖励的关联
	 * @param $micontentId	/内容id
	 * @param null $shareRewardId	/奖励id
	 */
	public function saveMicontentShareReward($micontentId,$rewardId=null)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$miContent_tab = M("micontent");
		Session::switchCustomer($cid);
		$retSave = $miContent_tab->where(['id'=>$micontentId])->save([
			'rewardId'=>$rewardId
		]);
		if(!is_numeric($retSave)){
			Log::write('内容关联奖励cid:'.$cid.'|sql:'.$miContent_tab->getLastSql());
			Output::instance()->object([
				'code'=>-1,
				'msg'=>'保存失败',
				'result'=>[]
			]);
			return;
		}
		Output::instance()->object([
			'code'=>0,
			'msg'=>'保存成功',
			'results'=>[]
		]);
	}
	/**
	 * 单篇内容获取达标用户奖励列表
	 * @param $rewardId 	/奖励id
	 * @param $micontentId	/内容id
	 * @param null $search	/搜索
	 * @param int $start	/分页
	 * @param int $limit
	 * @param string $order	/排序
	 * @param string $by
	 * @param int $excel	/0返回1导Excel
	 */
	public function getShareRewardList($rewardId,$micontentId,$search=null,$start=0,$limit=10,$order='createTime',
									   $by='desc',$excel=0)
	{
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$shareRewardRet_tab = M('share_reward_result');
		Session::switchCustomer($cid);
		$map = [];
		if($search){
			$map['b.nickname|a.fullName'] = ['like', '%'.$search.'%'];
		}
		$map['a.cid'] = $cid;
		$map['a.rewardId'] = $rewardId;
		$map['a.moduleId'] = $micontentId;
		$map['a.module'] = 'micontent';

		if($excel){
			$rewardRetList = $shareRewardRet_tab->alias('a')
				->join('wx_'.$cid.'_user_weixin_info b on a.uid=b.userId')
				->join('wx_'.$cid.'_user c on a.uid=c.id')
				//->join('inner join wx_share_reward_visit_result d on d.rewardId=a.rewardId and a.uid=d.uid')
				->field('a.*,b.nickname,b.headimgurl,c.phone as userPhone,c.fullName as userFullName')
				->where($map)
				->order('a.'.$order.' '.$by)
				->select();
		}else{
			$rewardRetList = $shareRewardRet_tab->alias('a')
				->join('wx_'.$cid.'_user_weixin_info b on a.uid=b.userId')
				->join('wx_'.$cid.'_user c on a.uid=c.id')
				->field('a.*,b.nickname,b.headimgurl,c.phone as userPhone,c.fullName as userFullName')
				->where($map)
				->order('a.'.$order.' '.$by)
				->limit($start, $limit)
				->select();
		}
		//echo $shareRewardRet_tab->getLastSql();exit;
		if($rewardRetList == null){
			Log::write('暂无奖励cid:'.$cid.'|sql:'.$shareRewardRet_tab->getLastSql());
			Output::instance()->object([
				'code'=>-1,
				'msg'=>'暂无数据',
				'results'=>[]
			]);
			return;
		}
		foreach($rewardRetList as $k=>$v){
			$v['statusNum'] = $v['status'];
			$v['contactInfo'] = '';
			switch($v['rewardWay']){
				case 1:
					$v['rewardWay'] = '红包';
					$rewardCfg = json_decode($v['rewardJson'], true);
					if($v['rewardCause'] == 1){
						if(!$v['status']){
							$v['status'] = '待发放'.$rewardCfg['redMoney'].'元';
						}else{
							$v['status'] = '已发放'.$rewardCfg['redMoney'].'元';
						}
					}else{
						if(!$v['status']){
							$v['status'] = '待发放'.$rewardCfg['clueRedMoney'].'元';
						}else{
							$v['status'] = '已发放'.$rewardCfg['clueRedMoney'].'元';
						}
					}
					$v['contactInfo'] = '';
					if($v['userFullName'] && $v['userPhone']){
						$v['contactInfo'] = '姓名:'.$v['userFullName'].'|手机:'.$v['userPhone'];
					}
					break;
				case 2:
					if($v['status']){
						$v['status'] = '已发放';
					}else{
						$v['status'] = '待发放';
					}
					$v['rewardWay'] = '实物礼品';
					$v['contactInfo'] = '';
					if($v['fullName'] && $v['phone']){
						$v['contactInfo'] = '姓名:'.$v['fullName'].'|手机:'.$v['phone'].'|地址:'.$v['address'];
					}
					break;
				case 3:
					if($v['status']){
						$v['status'] = '已发放';
					}else{
						$v['status'] = '待发放';
					}
					$v['contactInfo'] = '';
					if($v['fullName'] && $v['phone']){
						$v['contactInfo'] = '姓名:'.$v['fullName'].'|手机:'.$v['phone'];
					}
					$v['rewardWay'] = '虚拟礼品';
					break;
			}
			switch($v['rewardCause']){
				case 1:
					$v['rewardCause'] = '分享浏览人数达标';
					break;
				case 2:
					$v['rewardCause'] = '线索人数达标';
					break;
			};
			if($v['rewardJson']){
				$v['rewardJson'] = json_decode($v['rewardJson'], true);
			}
			$rewardRetList[$k] = $v;
		}
		if(!$excel){
			$total = $shareRewardRet_tab->alias('a')
				->join('wx_'.$cid.'_user_weixin_info b on a.uid=b.userId')
				->join('wx_'.$cid.'_user c on a.uid=c.id')
				->field('a.*,b.headimgurl,b.nickname,c.phone as userPhone,c.fullName as userFullName')
				->where($map)
				->count();
			Output::instance()->object([
				'code'=>0,
				'total'=>$total,
				'results'=>$rewardRetList
			]);
		}else{
			$excelDate = $excelArr = [];
			foreach($rewardRetList as $key=>$val){
				$excelDate['nickname'] = $val['nickname'];
				$excelDate['rewardCause'] = $val['rewardCause'];
				$excelDate['rewardWay'] = $val['rewardWay'];
				$excelDate['shareVisitNum'] = $val['shareVisitNum'];
				$excelDate['contactInfo'] = $val['contactInfo'];
				$excelDate['status'] = $val['status'];
				$excelArr[] = $excelDate;
			}
			$excelFileName = $rewardRetList[0]['rewardName'].'获奖名单'.date('Y-m-d H:i:s');
			$excelCellName = [
				['nickname','昵称'],
				['rewardCause','奖励原因'],
				['rewardWay','奖励方式'],
				['visitCount','分享浏览人数'],
				['contactInfo','联系方式'],
				['status','状态']
			];
			Output::instance()->objArrayExcel($excelFileName,$excelCellName,$excelArr);
		}
	}
}